// import 'package:flutter/material.dart';
// import 'package:image_picker/image_picker.dart';
// import 'dart:io';
// import 'analysis_result_page.dart';

// class DiagnosisPage extends StatefulWidget {
//   const DiagnosisPage({Key? key}) : super(key: key);

//   @override
//   State<DiagnosisPage> createState() => _DiagnosisPageState();
// }

// class _DiagnosisPageState extends State<DiagnosisPage> {
//   File? _image;
//   final _symptomsController = TextEditingController();
//   final _historyController = TextEditingController();
//   final _familyHistoryController = TextEditingController();

//   Future<void> _pickImage() async {
//     final ImagePicker picker = ImagePicker();

//     // 显示选择对话框
//     showModalBottomSheet(
//       context: context,
//       builder: (BuildContext context) {
//         return SafeArea(
//           child: Column(
//             mainAxisSize: MainAxisSize.min,
//             children: [
//               ListTile(
//                 leading:
//                     const Icon(Icons.photo_library, color: Color(0xFF1DC4A0)),
//                 title: const Text('从相册选择'),
//                 onTap: () async {
//                   Navigator.pop(context);
//                   final XFile? image = await picker.pickImage(
//                     source: ImageSource.gallery,
//                     maxWidth: 1920,
//                     maxHeight: 1080,
//                     imageQuality: 85,
//                   );
//                   if (image != null) {
//                     setState(() {
//                       _image = File(image.path);
//                     });
//                   }
//                 },
//               ),
//               ListTile(
//                 leading: const Icon(Icons.camera_alt, color: Color(0xFF1DC4A0)),
//                 title: const Text('拍照'),
//                 onTap: () async {
//                   Navigator.pop(context);
//                   final XFile? image = await picker.pickImage(
//                     source: ImageSource.camera,
//                     maxWidth: 1920,
//                     maxHeight: 1080,
//                     imageQuality: 85,
//                   );
//                   if (image != null) {
//                     setState(() {
//                       _image = File(image.path);
//                     });
//                   }
//                 },
//               ),
//             ],
//           ),
//         );
//       },
//     );
//   }

//   @override
//   Widget build(BuildContext context) {
//     return Scaffold(
//       backgroundColor: Colors.white,
//       appBar: AppBar(
//         backgroundColor: const Color(0xFF1DC4A0),
//         elevation: 0,
//         leading: IconButton(
//           icon: const Icon(Icons.arrow_back_ios, color: Colors.white),
//           onPressed: () => Navigator.pop(context),
//         ),
//         title: const Text(
//           '病因分析',
//           style: TextStyle(
//             color: Colors.white,
//             fontSize: 18,
//             fontWeight: FontWeight.w600,
//           ),
//         ),
//       ),
//       body: SingleChildScrollView(
//         padding: const EdgeInsets.all(20),
//         child: Column(
//           crossAxisAlignment: CrossAxisAlignment.start,
//           children: [
//             GestureDetector(
//               onTap: _pickImage,
//               child: Container(
//                 height: 200,
//                 width: double.infinity,
//                 decoration: BoxDecoration(
//                   color: Colors.grey[100],
//                   borderRadius: BorderRadius.circular(12),
//                   border: Border.all(color: Colors.grey[300]!),
//                 ),
//                 child: _image == null
//                     ? Column(
//                         mainAxisAlignment: MainAxisAlignment.center,
//                         children: [
//                           Image.asset(
//                             'assets/icons/upload_report.png',
//                             width: 60,
//                             height: 60,
//                             //color: const Color(0xFF1DC4A0),
//                           ),
//                           const SizedBox(height: 10),
//                           Text(
//                             '点击上传医学报告',
//                             style: TextStyle(
//                               color: Colors.grey[600],
//                               fontSize: 16,
//                               fontWeight: FontWeight.w500,
//                             ),
//                           ),
//                           const SizedBox(height: 5),
//                           Text(
//                             '支持jpg、png格式，最大10MB',
//                             style: TextStyle(
//                               color: Colors.grey[400],
//                               fontSize: 12,
//                             ),
//                           ),
//                           const SizedBox(height: 5),
//                           Row(
//                             mainAxisAlignment: MainAxisAlignment.center,
//                             children: [
//                               Icon(
//                                 Icons.photo_library,
//                                 size: 16,
//                                 color: Colors.grey[400],
//                               ),
//                               const SizedBox(width: 5),
//                               Text(
//                                 '相册',
//                                 style: TextStyle(
//                                   color: Colors.grey[400],
//                                   fontSize: 12,
//                                 ),
//                               ),
//                               const SizedBox(width: 20),
//                               Icon(
//                                 Icons.camera_alt,
//                                 size: 16,
//                                 color: Colors.grey[400],
//                               ),
//                               const SizedBox(width: 5),
//                               Text(
//                                 '拍照',
//                                 style: TextStyle(
//                                   color: Colors.grey[400],
//                                   fontSize: 12,
//                                 ),
//                               ),
//                             ],
//                           ),
//                         ],
//                       )
//                     : Stack(
//                         children: [
//                           ClipRRect(
//                             borderRadius: BorderRadius.circular(12),
//                             child: Image.file(
//                               _image!,
//                               fit: BoxFit.cover,
//                               width: double.infinity,
//                               height: double.infinity,
//                             ),
//                           ),
//                           Positioned(
//                             top: 8,
//                             right: 8,
//                             child: GestureDetector(
//                               onTap: () {
//                                 setState(() {
//                                   _image = null;
//                                 });
//                               },
//                               child: Container(
//                                 padding: const EdgeInsets.all(4),
//                                 decoration: BoxDecoration(
//                                   color: Colors.black.withOpacity(0.5),
//                                   shape: BoxShape.circle,
//                                 ),
//                                 child: const Icon(
//                                   Icons.close,
//                                   color: Colors.white,
//                                   size: 20,
//                                 ),
//                               ),
//                             ),
//                           ),
//                         ],
//                       ),
//               ),
//             ),
//             const SizedBox(height: 20),
//             _buildTextField(
//               controller: _symptomsController,
//               label: '症状描述',
//               hint: '请详细描述您的症状...',
//               maxLines: 3,
//             ),
//             const SizedBox(height: 20),
//             _buildTextField(
//               controller: _historyController,
//               label: '现病史',
//               hint: '请描述您的现有病史...',
//               maxLines: 3,
//             ),
//             const SizedBox(height: 20),
//             _buildTextField(
//               controller: _familyHistoryController,
//               label: '家族病史',
//               hint: '请描述您的家族病史...',
//               maxLines: 3,
//             ),
//             const SizedBox(height: 30),
//             SizedBox(
//               width: double.infinity,
//               height: 50,
//               child: ElevatedButton(
//                 onPressed: () {
//                   Navigator.push(
//                     context,
//                     MaterialPageRoute(
//                       builder: (context) => AnalysisResultPage(
//                         reportImage: _image,
//                         symptoms: _symptomsController.text,
//                         history: _historyController.text,
//                         familyHistory: _familyHistoryController.text,
//                       ),
//                     ),
//                   );
//                 },
//                 style: ElevatedButton.styleFrom(
//                   backgroundColor: const Color(0xFF1DC4A0),
//                   shape: RoundedRectangleBorder(
//                     borderRadius: BorderRadius.circular(25),
//                   ),
//                 ),
//                 child: const Text(
//                   '分析病因',
//                   style: TextStyle(
//                     fontSize: 16,
//                     fontWeight: FontWeight.w600,
//                   ),
//                 ),
//               ),
//             ),
//           ],
//         ),
//       ),
//     );
//   }

//   Widget _buildTextField({
//     required TextEditingController controller,
//     required String label,
//     required String hint,
//     int maxLines = 1,
//   }) {
//     return Column(
//       crossAxisAlignment: CrossAxisAlignment.start,
//       children: [
//         Text(
//           label,
//           style: const TextStyle(
//             fontSize: 16,
//             fontWeight: FontWeight.w600,
//           ),
//         ),
//         const SizedBox(height: 8),
//         TextField(
//           controller: controller,
//           maxLines: maxLines,
//           decoration: InputDecoration(
//             hintText: hint,
//             hintStyle: TextStyle(color: Colors.grey[400]),
//             filled: true,
//             fillColor: Colors.grey[100],
//             border: OutlineInputBorder(
//               borderRadius: BorderRadius.circular(12),
//               borderSide: BorderSide.none,
//             ),
//             contentPadding: const EdgeInsets.all(16),
//           ),
//         ),
//       ],
//     );
//   }

//   @override
//   void dispose() {
//     _symptomsController.dispose();
//     _historyController.dispose();
//     _familyHistoryController.dispose();
//     super.dispose();
//   }
// }

import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';
import 'analysis_result_page.dart';

class DiagnosisPage extends StatefulWidget {
  final String gender;
  final String age;
  final String bloodType;
  final String currentHistory;
  final String familyHistory;
  final String symptoms;

  const DiagnosisPage({
    Key? key,
    required this.gender,
    required this.age,
    required this.bloodType,
    required this.currentHistory,
    required this.familyHistory,
    required this.symptoms,
  }) : super(key: key);

  @override
  State<DiagnosisPage> createState() => _DiagnosisPageState();
}

class _DiagnosisPageState extends State<DiagnosisPage> {
  File? _image;
  late TextEditingController _genderController;
  late TextEditingController _ageController;
  late TextEditingController _bloodTypeController;
  late TextEditingController _symptomsController;
  late TextEditingController _historyController;
  late TextEditingController _familyHistoryController;

  @override
  void initState() {
    super.initState();
    // 使用 widget 参数初始化控制器
    _genderController = TextEditingController(text: widget.gender);
    _ageController = TextEditingController(text: widget.age);
    _bloodTypeController = TextEditingController(text: widget.bloodType);
    _symptomsController = TextEditingController(text: widget.symptoms);
    _historyController = TextEditingController(text: widget.currentHistory);
    _familyHistoryController =
        TextEditingController(text: widget.familyHistory);
  }

  Future<void> _pickImage() async {
    final ImagePicker picker = ImagePicker();

    final source = await showModalBottomSheet<ImageSource>(
      context: context,
      builder: (context) => SafeArea(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            ListTile(
              leading:
                  const Icon(Icons.photo_library, color: Color(0xFF1DC4A0)),
              title: const Text('从相册选择'),
              onTap: () => Navigator.pop(context, ImageSource.gallery),
            ),
            ListTile(
              leading: const Icon(Icons.camera_alt, color: Color(0xFF1DC4A0)),
              title: const Text('拍照'),
              onTap: () => Navigator.pop(context, ImageSource.camera),
            ),
          ],
        ),
      ),
    );

    if (source != null) {
      final image = await picker.pickImage(
        source: source,
        maxWidth: 1920,
        maxHeight: 1080,
        imageQuality: 85,
      );
      if (image != null) {
        setState(() => _image = File(image.path));
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        backgroundColor: const Color(0xFF1DC4A0),
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios, color: Colors.white),
          onPressed: () => Navigator.pop(context),
        ),
        title: const Text(
          '病因分析',
          style: TextStyle(
            color: Colors.white,
            fontSize: 18,
            fontWeight: FontWeight.w600,
          ),
        ),
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(20),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _buildImageUploadSection(),
            const SizedBox(height: 20),
            _buildPatientInfoSection(),
            const SizedBox(height: 30),
            _buildSubmitButton(),
          ],
        ),
      ),
    );
  }

  Widget _buildImageUploadSection() {
    return GestureDetector(
      onTap: _pickImage,
      child: Container(
        height: 200,
        width: double.infinity,
        decoration: BoxDecoration(
          color: Colors.grey[100],
          borderRadius: BorderRadius.circular(12),
          border: Border.all(color: Colors.grey[300]!),
        ),
        child: _image == null
            ? Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Image.asset(
                    'assets/icons/upload_report.png',
                    width: 60,
                    height: 60,
                  ),
                  const SizedBox(height: 10),
                  Text(
                    '点击上传医学报告',
                    style: TextStyle(
                      color: Colors.grey[600],
                      fontSize: 16,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                  const SizedBox(height: 5),
                  Text(
                    '支持jpg、png格式，最大10MB',
                    style: TextStyle(
                      color: Colors.grey[400],
                      fontSize: 12,
                    ),
                  ),
                ],
              )
            : ClipRRect(
                borderRadius: BorderRadius.circular(12),
                child: Stack(
                  children: [
                    Image.file(_image!, fit: BoxFit.cover),
                    Positioned(
                      top: 8,
                      right: 8,
                      child: IconButton(
                        icon: const Icon(Icons.close, color: Colors.white),
                        onPressed: () => setState(() => _image = null),
                      ),
                    ),
                  ],
                ),
              ),
      ),
    );
  }

  Widget _buildPatientInfoSection() {
    return Column(
      children: [
        _buildInfoField('性别', _genderController),
        const SizedBox(height: 20),
        _buildInfoField('年龄', _ageController),
        const SizedBox(height: 20),
        _buildInfoField('血型', _bloodTypeController),
        const SizedBox(height: 20),
        _buildMultiLineField('症状描述', _symptomsController),
        const SizedBox(height: 20),
        _buildMultiLineField('现病史', _historyController),
        const SizedBox(height: 20),
        _buildMultiLineField('家族病史', _familyHistoryController),
      ],
    );
  }

  Widget _buildInfoField(String label, TextEditingController controller) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          label,
          style: const TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.w600,
          ),
        ),
        const SizedBox(height: 8),
        TextField(
          controller: controller,
          decoration: InputDecoration(
            hintText: '请输入$label...',
            filled: true,
            fillColor: Colors.grey[100],
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(12),
              borderSide: BorderSide.none,
            ),
            contentPadding: const EdgeInsets.all(16),
          ),
        ),
      ],
    );
  }

  Widget _buildMultiLineField(String label, TextEditingController controller) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          label,
          style: const TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.w600,
          ),
        ),
        const SizedBox(height: 8),
        TextField(
          controller: controller,
          maxLines: 3,
          decoration: InputDecoration(
            hintText: '请详细描述您的$label...',
            filled: true,
            fillColor: Colors.grey[100],
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(12),
              borderSide: BorderSide.none,
            ),
            contentPadding: const EdgeInsets.all(16),
          ),
        ),
      ],
    );
  }

  Widget _buildSubmitButton() {
    return SizedBox(
      width: double.infinity,
      height: 50,
      child: ElevatedButton(
        style: ElevatedButton.styleFrom(
          backgroundColor: const Color(0xFF1DC4A0),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(25),
          ),
        ),
        onPressed: () {
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => AnalysisResultPage(
                reportImage: _image,
                gender: _genderController.text,
                age: _ageController.text,
                bloodType: _bloodTypeController.text,
                symptoms: _symptomsController.text,
                history: _historyController.text,
                familyHistory: _familyHistoryController.text,
              ),
            ),
          );
        },
        child: const Text(
          '分析病因',
          style: TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.w600,
            color: Colors.white,
          ),
        ),
      ),
    );
  }

  @override
  void dispose() {
    _genderController.dispose();
    _ageController.dispose();
    _bloodTypeController.dispose();
    _symptomsController.dispose();
    _historyController.dispose();
    _familyHistoryController.dispose();
    super.dispose();
  }
}
